import time
from openpyxl import load_workbook


class ReadLog:
    # 日志文件路径
    log_path = 'C:/Users/qaz24/Desktop/duxiaoman.log'
    # excel文件路径
    book = load_workbook(filename='D:/codes/Python/job/AppAutoTest/log.xlsx')
    st = book.worksheets[0]
    F_num = 0
    E_num = 0
    W_num = 0
    I_num = 0
    D_num = 0

    def readlog(self, row_location):
        # with open方式打开更安全，且会自动关闭，不用写f.close()
        with open(self.log_path, 'r', encoding='utf-8') as f:
            lines = f.readlines()
            for line in lines:
                # if len(line) > 33:
                #     if line[30] == ' ' and line[32] == ' ':
                #         if line[31] == 'F':
                #             self.F_num += 1
                #         elif line[31] == 'E':
                #             self.E_num += 1
                #         elif line[31] == 'W':
                #             self.W_num += 1
                #         elif line[31] == 'I':
                #             self.I_num += 1
                #         elif line[31] == 'D':
                #             self.D_num += 1

                # 防止下面段落出现数组越界错误
                if len(line) > 2:
                    # 识别标识数量
                    if line[0] == 'F' and line[1] == '/':
                        self.F_num += 1
                    elif line[0] == 'E' and line[1] == '/':
                        self.E_num += 1
                    elif line[0] == 'W' and line[1] == '/':
                        self.W_num += 1
                    elif line[0] == 'I' and line[1] == '/':
                        self.I_num += 1
                    elif line[0] == 'D' and line[1] == '/':
                        self.D_num += 1
            # 对日志文件执行保存操作，使每次读取日志文件时都能读取到新增加的内容
            f.flush()
        # 这句没什么用
        print(self.st)
        # st.cell()，第一个参数指定要插入的行的位置，第二个参数指定要插入的列的位置
        self.st.cell(row_location, 1).value = self.F_num
        self.F_num = 0
        self.st.cell(row_location, 2).value = self.E_num
        self.E_num = 0
        self.st.cell(row_location, 3).value = self.W_num
        self.W_num = 0
        self.st.cell(row_location, 4).value = self.I_num
        self.I_num = 0
        self.st.cell(row_location, 5).value = self.D_num
        self.D_num = 0
        # 插入之后保存文件的更改，这一步一定要有
        self.book.save('D:/codes/Python/job/AppAutoTest/log.xlsx')


# 这个数字的作用是指定本次在excel插入时所在的行数，在上面的st.cell()里面使用
row_location = 2
while True:
    readlog = ReadLog()
    readlog.readlog(row_location)
    # +1保证下一次插入在下一行
    row_location += 1
    time.sleep(2)
